source('codes/00_import_libraries.R')


#-----------------------------------------------------------------------------#
# data ------------------------------------------------------------------------
#-----------------------------------------------------------------------------#

dict_name = 'base'
gw = readRDS('input/gw_macro_predictors.RDS')$dt
dt = readRDS('input/combined_data.rds')[[dict_name]] %>% 
  mutate(across(starts_with('mkt'), ~.x*12)) %>% 
  select(-OG) %>% 
  left_join(gw, by = 'ym')

# names(dt) = str_replace_all(names(dt), '_', ' ')


#-----------------------------------------------------------------------------#
# function --------------------------------------------------------------------
#-----------------------------------------------------------------------------#

ols_res = function(dt, x_list, y = 'mkt1', h = 1, panel_name, fs) {
  
  mod_list = lapply(x_list, function(x) {
    fn_fit_ols(
      df   = dt, 
      xvar = x, 
      yvar = y)
  })
  
  mod_robust = lapply(mod_list, function(mod) {
    coeftest(mod, vcov. = NeweyWest(mod, lag=h, prewhite=FALSE))
  })
  
  r2 = lapply(mod_list, function(mod) glance(mod)$adj.r.squared * 100)
  
  coefs = x_list[[length(x_list)]]
  names(coefs) = coefs %>% str_replace_all('_', ' ') %>% tools::toTitleCase()
  
  out = huxreg(
    mod_robust,
    coefs           = coefs,
    error_format    = '({statistic})',
    stars           = c(`***` = 0.01, `**` = 0.05, `*` = 0.1),
    statistics      = c(0),
    borders         = 0,
    outer_borders   = 0,
    note            = NULL
  )
  
  rbind(out, c('$R^2$', r2)) %>% 
    set_number_format(-1, -1, 2) %>% 
    set_align(1, everywhere, 'center') %>% 
    set_tb_borders(1, everywhere, 0.8) %>%
    set_bottom_border(final(1), everywhere, 0.8) %>% 
    set_all_padding(0) %>% 
    set_escape_contents(F) %>%
    set_font_size(fs)
}



#-----------------------------------------------------------------------------#
# function --------------------------------------------------------------------
#-----------------------------------------------------------------------------#

narr_list = readRDS('input/narrative_dicts_v2.rds')[[dict_name]] %>% names()
macro_list = c('DP', 'EP', 'DE', 'SVAR', 'TBL')
# x_list = list(c('War', 'DP', 'EP', 'SVAR', 'TBL'))


fn_create_list = function(z_list) {
  x_list = lapply(z_list, function(z) {
    c('War', z)
  })
  c(x_list, list(c('War', z_list)))
}


out1 = ols_res(
  dt         = dt, 
  x_list     = fn_create_list(macro_list),
  panel_name = 'Panel A: Macroeconomic Predictors',
  fs         = 11
)
quick_xlsx(out1, file = 'output/tables/Table_5A.xlsx')


out2 = ols_res(
  dt         = dt,
  x_list     = fn_create_list(narr_list[-1]),
  panel_name = 'Panel B: Narrative Predictors',
  fs = 11
)
quick_xlsx(out2, file = 'output/tables/Table_5B.xlsx')







